package repository

import (
	"context"
	"time"

	"github.com/we-pay-kit/we-pay-kit/internal/db"
)

type CouponIssue struct {
	ID           int64
	ActivityID   int64
	PackageID    int64
	PhoneNumber  string
	UserID       *string
	CouponID     string
	CouponAmount float64
	IssueTime    time.Time
	Status       string
	FailReason   *string
}

type CouponIssueRepository struct{ db *db.DB }

func NewCouponIssueRepository(database *db.DB) *CouponIssueRepository {
	return &CouponIssueRepository{db: database}
}

func (r *CouponIssueRepository) Create(ctx context.Context, c *CouponIssue) (int64, error) {
	q := `INSERT INTO cash_coupon_issue(activity_id, package_id, phone_number, user_id, coupon_id, coupon_amount, issue_time, status, fail_reason)
          VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9) RETURNING id`
	var id int64
	err := r.db.QueryRowContext(ctx, q, c.ActivityID, c.PackageID, c.PhoneNumber, c.UserID, c.CouponID, c.CouponAmount, c.IssueTime, c.Status, c.FailReason).Scan(&id)
	return id, err
}

func (r *CouponIssueRepository) ListByActivity(ctx context.Context, activityID int64, limit, offset int) ([]CouponIssue, error) {
	if limit <= 0 {
		limit = 20
	}
	q := `SELECT id, activity_id, package_id, phone_number, user_id, coupon_id, coupon_amount, issue_time, status, fail_reason
          FROM cash_coupon_issue WHERE activity_id=$1 ORDER BY id DESC LIMIT $2 OFFSET $3`
	rows, err := r.db.QueryContext(ctx, q, activityID, limit, offset)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	res := make([]CouponIssue, 0, limit)
	for rows.Next() {
		var c CouponIssue
		var uid, fr *string
		if err := rows.Scan(&c.ID, &c.ActivityID, &c.PackageID, &c.PhoneNumber, &uid, &c.CouponID, &c.CouponAmount, &c.IssueTime, &c.Status, &fr); err != nil {
			return nil, err
		}
		c.UserID = uid
		c.FailReason = fr
		res = append(res, c)
	}
	return res, rows.Err()
}
